import { Injectable } from '@nestjs/common';
import {
  CashBack_Create_Dto,
  CashBack_Find_Dto,
  CashBack_OrderListFind_Dto,
  CashBack_Pass_Dto,
} from './assets/cashBack.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { CashBack } from './assets/cashBack.entity';
import { EntityManager, Repository } from 'typeorm';
import { util_Db_PageList } from '@/common/util/db';
import { IRequest } from '@/common/typeScripts';
import {
  Constant_Enum_Enum_CashBack_Status,
  Constant_Enum_Enum_CashBack_Way,
  Constant_Enum_Enum_Rebates_DistributionStatus,
} from '@/common/constants/enum';
import { Class_HttpException_Base } from '@/common/classes/httpException';
import { UserClient } from '../userClient/assets/userClient.entity';
import { Rebates } from '../rebates/assets/rebates.entity';

@Injectable()
export class CashBack_Service {
  constructor(
    @InjectRepository(Rebates)
    private rebates_Repository: Repository<Rebates>,
    @InjectRepository(CashBack)
    private cashBack_Repository: Repository<CashBack>,
    @InjectRepository(UserClient)
    private userClient_Repository: Repository<UserClient>,
    private entityManager: EntityManager,
  ) {}

  async cashBack_FindByPage(query: CashBack_Find_Dto) {
    return await util_Db_PageList<CashBack>({
      queryBuilder: this.cashBack_Repository
        .createQueryBuilder('cashBack')
        .leftJoin('cashBack.userClient', 'userClient')
        .where(!query.cashStartTime ? '1=1' : 'cashBack.cashBackTime >= :cashStartTime', {
          cashStartTime: query.cashStartTime,
        })
        .andWhere(!query.cashEndTime ? '1=1' : 'cashBack.cashBackTime <= :cashEndTime', {
          cashEndTime: query.cashEndTime,
        })
        .select([
          'cashBack.id AS id',
          'cashBack.applyMoney AS applyMoney',
          'cashBack.createTime AS createTime',
          'cashBack.cashBackWay AS cashBackWay',
          'cashBack.status AS status',
          'cashBack.cashBackTime AS cashBackTime',
          'cashBack.cashBackImg AS cashBackImg',
          'userClient.id AS userClientId',
          'userClient.userName AS userName',
        ]),
      query: {
        'userClient.id': query.userClientId,
        'userClient.userName': query.userClientName,
        status: query.status,
      },
      isRaw: true,
    });
  }

  async cashBack_Static(query: CashBack_Find_Dto) {
    const cashbackAllMoney = await this.cashBack_Repository
      .createQueryBuilder('cashBack')
      .leftJoin('cashBack.userClient', 'userClient')
      .where(!query.cashStartTime ? '1=1' : 'cashBack.cashBackTime >= :cashStartTime', {
        cashStartTime: query.cashStartTime,
      })
      .andWhere(!query.cashEndTime ? '1=1' : 'cashBack.cashBackTime <= :cashEndTime', {
        cashEndTime: query.cashEndTime,
      })
      .andWhere('userClient.id=:userClientId', { userClientId: query.userClientId })
      .andWhere('cashBack.status=:cashBackStatus', {
        cashBackStatus: Constant_Enum_Enum_CashBack_Status.CashBack_Status_Transfered,
      })
      .andWhere('userClient.userName=:userName', { userName: query.userClientName })
      .select('SUM(cashBack.applyMoney)', 'applyMoney')
      .getOne();
    return cashbackAllMoney || 0;
  }

  async cashBack_FindOneById(id: number) {
    return await this.cashBack_Repository
      .createQueryBuilder('cashBack')
      .andWhere(`cashBack.id = :id`, { id: id })
      .getOne();
  }

  async cashBack_Pass(body: CashBack_Pass_Dto) {
    const cashBack = await this.cashBack_FindOneById(body.id);
    if (cashBack.cashBackWay == Constant_Enum_Enum_CashBack_Way.CashBack_Way_ZfbHand) {
      if (!body.cashBackImg) new Class_HttpException_Base('请上传支付宝打款截图');
    }
    const rebatess = await this.rebates_Repository
      .createQueryBuilder('rebates')
      .andWhere('rebates.cashBackId = :cashBackId', { cashBackId: body.id })
      .getMany();
    const rebatesss: Rebates[] = [];
    rebatess.map((item) => {
      item.rebatesStatus =
        Constant_Enum_Enum_Rebates_DistributionStatus.InviteRelation_DistributionStatus_Accouted;
    });
    return await this.entityManager.transaction(async (manage) => {
      manage.save(rebatesss);
      cashBack.status = Constant_Enum_Enum_CashBack_Status.CashBack_Status_Transfered;
      cashBack.cashBackImg = body.cashBackImg;
      await manage.save(cashBack);
      return '手动打款成功';
    });
  }

  async cashBack_Web_Submit(body: CashBack_Create_Dto, req: IRequest) {
    const rebatess = await this.rebates_Repository
      .createQueryBuilder('rebates')
      .leftJoin('rebates.invitee', 'invitee')
      .where('rebates.status = :status', {
        status: Constant_Enum_Enum_Rebates_DistributionStatus.InviteRelation_DistributionStatus_OutGoed,
      })
      .andWhere('rebates.createTime > :currentTime', { currentTime: new Date().getTime() })
      .getMany();

    return await this.entityManager.transaction(async (manage) => {
      if (body.cashBackWay == Constant_Enum_Enum_CashBack_Way.CashBack_Way_ZfbHand) {
        const cashBack = await manage.save(CashBack, {
          userClient: this.userClient_Repository.create({ id: req.user.userId }),
          applyMoney: body.applyMoney,
          cashBackWay: body.cashBackWay,
        });
        rebatess.forEach((item) => {
          item.cashBack = this.cashBack_Repository.create({ id: cashBack.id });
          item.rebatesStatus =
            Constant_Enum_Enum_Rebates_DistributionStatus.InviteRelation_DistributionStatus_Accouting;
        });
        manage.save(rebatess);
      }
      return '提交申请成功';
    });
  }

  async cashBack_Web_FindByPage(query: CashBack_Find_Dto, req: IRequest) {
    return await util_Db_PageList<CashBack>({
      queryBuilder: this.cashBack_Repository
        .createQueryBuilder('cashBack')
        .leftJoinAndSelect('cashBack.userClient', 'userClient'),
      query: {
        userClient: req.user.userId,
      },
    });
  }

  async cashBack_FindOrderListByPage(query: CashBack_OrderListFind_Dto) {
    return await util_Db_PageList<CashBack>({
      queryBuilder: this.cashBack_Repository
        .createQueryBuilder('cashBack')
        .leftJoin('cashBack.userClient', 'userClient')
        .leftJoin(
          'Order',
          'order',
          'order.userClientId = userClient.id AND order.createTime < cashBack.createTime',
        )
        .leftJoin('order.orderVirtualDetail', 'orderVirtualDetail')
        .leftJoin('orderVirtualDetail.good', 'good')
        .leftJoin('order.rebates', 'rebates')
        .leftJoin('good.product', 'product')
        .leftJoin('product.platform', 'platform')
        .leftJoin(
          'distributionrate',
          'distributionrate',
          ` (distributionrate.userClientId = userClient.id OR distributionrate.userClientId IS NULL)
           AND product.id = distributionrate.productId`,
        )
        .select([
          'userClient.id AS userClientId',
          'userClient.userName AS userName',
          'order.id AS orderId',
          'order.createTime AS orderCreateTime',
          'order.status AS orderStatus',
          'order.payPrice AS payPrice',
          'order.createTime AS createTime',
          'product.productName AS productName',
          'platform.platFormName AS platFormName',
          'rebates.rebatesType AS rebatesType',
          'rebates.rebatesMoney AS rebatesMoney',
          'distributionrate.firstOrderRate AS firstOrderRate',
          'distributionrate.secondOrderRate AS secondOrderRate',
        ]),
      // .where(
      //   new Brackets((qb) => {
      //     qb.where('order.status = :payStatus', {
      //       payStatus: Constant_Enum_Enum_Order_PayStatus.order_PayStatus_Pay,
      //     }).orWhere('order.status = :refundStatus', {
      //       refundStatus: Constant_Enum_Enum_Order_PayStatus.order_PayStatus_Refund,
      //     });
      //   }),
      // )
      // .setParameters({
      //   payStatus: Constant_Enum_Enum_Order_PayStatus.order_PayStatus_Pay,
      //   refundStatus: Constant_Enum_Enum_Order_PayStatus.order_PayStatus_Refund,
      // }),
      query: {
        page: query.page,
        size: query.size,
        'cashBack.id': query.id,
      },
      isRaw: true,
      getQuery: true,
    });
  }
}
